﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WLMCoreLibrary;
using MiWebSite_Core;

namespace MWS_AddDirectory.MisAnuncios
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["username"] != null)
            {
                doLogonUser(Request["username"], Request["password"], false);
            }
            if (!IsPostBack)
            {
                lblDirectorio.Text = lblDirectorio2.Text = lblDirectorio3.Text = DeCurrentDomain.DomainName;

            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            doLogonUser(username.Text, password.Text, false);
        }

        /// <summary>
        /// Does the logon user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <param name="rememberUser">if set to <c>true</c> [remember user].</param>
        protected void doLogonUser(string userName, string Password, Boolean rememberUser)
        {

            //TODO: REvista esta funcion para no dejar conexiones abiertas
            WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();

            dbConnector ConexionDB = new dbConnector(config.Connections[0].value);
            MiWebSiteUser usuario = new MiWebSiteUser(WLMFunctions.CleanQuery(userName), ref ConexionDB);
            if (usuario.password == WLMFunctions.CleanQuery(Password))
            {

                if (rememberUser)
                    CurrentUser.LogOnUser(usuario, rememberUser);
                else
                    CurrentUser.LogOnUser(usuario);
                ConexionDB.CloseConnection();

                //Response.Redirect("/");
            }
            else
            {
                
                Cliente cliente = new Cliente(userName, ref ConexionDB);
                if (cliente.id != 0)
                {
                    SaltedHash hash = new SaltedHash();
                    string passCripted = hash.GetStringHash(Password, cliente.salt);
                    if (passCripted == cliente.password)
                    {
                        CurrentClient.ClientLogin(cliente);
                        ConexionDB.CloseConnection();

                        SuccessObject success = new SuccessObject();
                        success.Code = SuccessCode.UserLogged;
                        success.Message = "Usuario Logeado Correctamente";
                        success.Object = WLMFunctions.SerializeObject(cliente);
                        Response.ContentType = "text/xml";
                        Response.Write(WLMFunctions.SerializeObject(success, true));
                        Response.End();
                    }
                    ErrorObject errorLog = new ErrorObject(ErrorCode.UserWrongPassword, "Password Equivocado");
                    Response.ContentType = "text/xml";
                    Response.Write(WLMFunctions.SerializeObject(errorLog, true));
                    Response.End();
                }

            }
            if (ConexionDB.connector.State == System.Data.ConnectionState.Open)
                ConexionDB.CloseConnection();
            ErrorObject error = new ErrorObject(ErrorCode.UserDontExist,"El Usuario no Existe");
            Response.ContentType = "text/xml";
            Response.Write(WLMFunctions.SerializeObject(error,true));
            Response.End();
        }
    }
}